<template>
	<view class="zwyVideoBox" :style="{ height: playerH, top: playerT + 'px' }">
		<video :object-fit="videoInfo['objectFit'] ? videoInfo['objectFit'] : 'contain'" :src="videoUrl ? videoUrl : ''"
			id="videoPlayer" style="background:black;" :autoplay="index == currentIndex" class="zwyVideo" @ended="isEnded"
			:enable-progress-gesture="false" :show-fullscreen-btn="false" @play="play" @timeupdate="timeupdate" @error="videoError"
			:controls="false" :enable-play-gesture="false" @loadedmetadata="viewStatus">
			<view @click.stop="videoClick($event)" style="width: 100vw;height: 100vh;position: relative;z-index: 99;"></view>
			<zwyLoading v-if="index == currentIndex && showLoading"></zwyLoading>
		</video>

		
		<zwyVideoProgress @isPause="isPause" @playNow="playNow" v-if="index == currentIndex" v-show="isHideBars"
			:isHideBars="isHideBars" :isPlayNow="isPlayNow" :currentTime="currentTime" :duration="duration"
			@isChangingFunc="isChangingFunc" @sliderEnd="sliderEnd"></zwyVideoProgress>
		<insertAdTt ref="insertAdTt" />
	</view>
</template>

<script>
import zwyVideoProgress from './zwyVideoProgress.vue';
import insertAdTt from './insertAdTt.vue';
const util = require('../../../util/util.js');
export default {
	name: 'zwyVideo',
	components: {
		zwyVideoProgress,
		insertAdTt
	},
	props: {
		isHideBars: {
			type: Boolean,
			default: false
		},
		playerT: {
			type: Number,
			default: 0
		},
		totalFreeTime: {
			type: Number,
			default: 0
		},
		
		playerH: {
			type: String,
			default: '100%'
		},
		videoInfo: {
			type: Object,
			default: {}
		},
		videoUrl: {
			type: String,
			default: ''
		},
		index: {
			type: Number,
			default: -2
		},
		currentIndex: {
			type: Number,
			default: -1
		},
		templateIds: {
			type: Array,
			default: []
		},
		imageArr: {
			type: Array,
			default: []
		},
		pauseNum: {
			type: Number,
			default: 0
		},
	},
	watch: {
		/* val监听改变的值*/
		currentIndex(val) {
			console.log(val, '监听方法');
			this.playNow(val);
		},
		pauseNum: {
			handler(val) {
				this.$nextTick(() => {
					console.log(val, 'pauseNum-----------pauseNum---------------pauseNum-------------pauseNum--------------pauseNum');
					if (val != 0) {
						this.isPause()
					} else {
						this.playNow();
					}
				})
			},
			immediate: true,
		},
	},
	data() {
		return {
			currentTime: 0,
			duration: 0,
			isPlayNow: false,
			videoContent: '',
			showLoading: true,
			reqNum: 0,
			touchTag: true,
			curTime: 0,
			touchendTime: new Date().getTime(),
			touchNum: 0,
			dbClick: false,
			isIos: getApp().globalData.isIos,
			showFlag: true,
			nowVideoView: false,
			insertAdTt: false,
			newVideoListIn: false
		};
	},
	created() {
		let compilationId = this.videoInfo && (this.videoInfo.episodicDrama || {}).compilationsId
		if(compilationId && [240].includes(compilationId)) {
			this.newVideoListIn = true
		} else {
			this.newVideoListIn = false
		}
	},
	mounted() {
		this.isIos = getApp().globalData.isIos
		console.log('mounted-----',this.pauseNum);
		this.videoContent = uni.createVideoContext('videoPlayer', this);
		if(this.pauseNum == 0){
			this.playNow();
		}
		
	},

	methods: {
		viewStatus() {
			this.nowVideoView = true
		},
		videoError(error) {
			console.log('video-err', error)
			let {
				detail
			} = error
			this.errorPopupVideo({
				videoUrl: this.videoUrl,
				...(detail || {})
			})
		},
		// touchStart(){
		// 	this.touchTag=false;
		// 	console.log("touchStart")
		// },
		videoClick(e) {
			this.touchNum++
			console.log(this.touchNum)
			if (this.touchNum > 1) {
				this.$emit('dbClick', e)
				this.handleAddMess()
			} else {
				setTimeout(() => {
					if (this.touchNum == 1 && !this.dbClick) {
						this.$emit('videoClick');
					}
					if (this.touchNum >= 2) {
						this.dbClick = true
						setTimeout(() => {
							this.dbClick = false
						}, 1000)
						this.$emit('dbClick', e)
						this.handleAddMess()
					}
					this.touchNum = 0
				}, 250)
			}

		},
		async handleAddMess() {
			console.log(this.templateIds, 'this.templateIds');
			try {
				let res = await uni.requestSubscribeMessage({
					tmplIds: this.templateIds || []
				})
				console.log('res=====', res)
				if ((res[0] || {}).errCode === 10001027 || (res[0] || {}).errMsg === 'requestSubscribeMessage:fail') {
					uni.showToast({
						title: `请去设置开启订阅消息`,
						icon: 'none'
					})

					// 弹窗拉取失败
					this.$uma.trackEvent('Ume_Subscribe', {
						name: 'Ume_Subscribe_sign_in_fail'
					})
				}

				let template = []
				let temResult = res[1] || {}

				if (temResult[this.templateIds[0]] === 'accept') {
					// 弹窗拉取允许
					this.$uma.trackEvent('Ume_Subscribe', {
						name: 'Ume_Subscribe_sign_in_agree'
					})
				} else if (temResult[this.templateIds[0]] === 'reject') {
					// 弹窗拉取拒绝
					this.$uma.trackEvent('Ume_Subscribe', {
						name: 'Ume_Subscribe_sign_in_disagree'
					})
				}
				// 添加订阅模板
				if (
					temResult[this.templateIds[0]] === 'accept' ||
					temResult[this.templateIds[1]] === 'accept' ||
					temResult[this.templateIds[2]] === 'accept'
				) {
					if (temResult[this.templateIds[0]] === 'accept') { // 签到类型
						template.push({
							templateId: this.templateIds[0],
							templateType: 3
						})
					}

					if (temResult[this.templateIds[1]] === 'accept') { // 剧集更新类型
						template.push({
							templateId: this.templateIds[1],
							templateType: 1
						})
					}

					if (temResult[this.templateIds[2]] === 'accept') { // 热播新剧提醒类型
						template.push({
							templateId: this.templateIds[2],
							templateType: 2
						})
					}
					this.addDingMess(template)
				}
			} catch (error) {
				console.log(error)
			}
		},
		// 订阅上报
		async addDingMess(template) {
			try {
				let res = await this.zwyRequest({
					url: '/mp-api/user_one_time_subscribe/batch',
					method: 'POST',
					data: {
						sourceType: 3,
						sourceId: 0,
						sourceDesc: '',
						templates: template
					}
				})
				console.log('dasdddddd=====', res)
			} catch (error) {
				console.log(error)
			}
		},
		isPause(type) {
			// console.log(type, 'type');
			if (type == 'handPause') {
				const currentTimestamp = Math.floor(Date.now() / 1000);
				if (currentTimestamp - getApp().globalData.lastAdTimestamp > 180 && !getApp().globalData.isAdComeCheck) {
					// 曝光插屏广告
					// #ifdef MP-TOUTIAO
					this.$refs.insertAdTt && this.$refs.insertAdTt.isShowAd()
					// #endif
					console.log('Show interstitial ad');
					// getApp().globalData.lastAdTimestamp = currentTimestamp;
				} else {
					console.log('Skip interstitial ad');
				}
			}
			// _this.videoContent.pause();
			// _this.isPlayNow = false;
			if (this.videoContent != "" && this.nowVideoView) {
				this.videoContent.pause();
				this.isPlayNow = false;
			} else {
				if (this.reqNum < 8) {
					this.reqNum++
					setTimeout(() => {
						this.isPause()
					}, 500)
				}
			}
		},
		isChangingFunc() {
			this.isChanging = true;
		},
		sliderEnd(e) {
			console.log('sliderEnd', e);
			let nowTime = e;
			console.log('sliderEnd', nowTime);
			this.videoContent.seek(nowTime);
			this.videoContent.play();
			this.isPlayNow = true;
			this.showLoading = true;
			clearTimeout(this.changeTimer);
			this.changeTimer = setTimeout(() => {
				this.isChanging = false;
			}, 500);
		},
		timeupdate(e) {
			if (e.detail.currentTime == this.currentTime) {
				if (!this.showLoading) this.showLoading = true;
			} else {
				if (this.showLoading) this.showLoading = false;
			}
			if (!this.isChanging) {
				this.currentTime = e.detail.currentTime;
				this.duration = e.detail.duration;
			}
			let compilationsId = this.videoInfo.episodicDrama.compilationsId
			let duration = getApp().globalData.zwyVideoDuration[compilationsId]
			let time = Math.round(this.currentTime)

			if (duration) {
				if (time > this.curTime) {
					// if(duration == 3 && this.touchTag == true){
					// 	this.$emit('hideBars');
					// 	console.log("进入全屏")
					// }
					this.curTime = time;
					duration++;
					// console.log("duration:%s",duration)
					getApp().globalData.zwyVideoDuration[compilationsId] = duration;
					if (duration >= this.totalFreeTime * 0.2) {
						if (this.showFlag) {
							if (this.isIos) {
								this.isShowIosGuide()
							} else {
								this.isShowGuide()
							}
						}
					}
				}
			} else {
				getApp().globalData.zwyVideoDuration[compilationsId] = 1;
			}
		},

		isShowGuide() {
			this.zwyRequest({
				url: '/cdp/personal/show/once/info?type=DOU_YIN_FAVORITE_ANDROID',
				header: {
					'content-type': 'application/json'
				},
				method: 'get'
			}).then(res => {
				if (res.show) {
					tt.showFavoriteGuide({
						type: "bar",
						content: "一键添加到「我的小程序」",
						position: "bottom",
						success(res) {
							console.log("引导组件展示成功", res);
						},
						fail(err) {
							console.log("引导组件展示失败", err);
						},
					});
					this.addAndroidGuide()
				}
				this.showFlag = false
				console.log('是否展示引导组件', res);
			});
		},
		isShowIosGuide() {
			this.zwyRequest({
				url: '/cdp/personal/show/once/daily/info?type=DOU_YIN_FAVORITE_IOS',
				header: {
					'content-type': 'application/json'
				},
				method: 'get'
			}).then(res => {
				if (res.show) {
					tt.showFavoriteGuide({
						type: "bar",
						content: "一键添加到「我的小程序」",
						position: "bottom",
						success(res) {
							console.log("引导组件展示成功", res);
						},
						fail(err) {
							console.log("引导组件展示失败", err);
						},
					});
					this.addIosGuide()
				}
				this.showFlag = false
				console.log('是否展示引导组件---ios', res);
			});
		},
		addAndroidGuide() {
			this.zwyRequest({
				url: '/cdp/personal/show/once/info/DOU_YIN_FAVORITE_ANDROID',
				header: {
					'content-type': 'application/json'
				},
				method: 'post'
			}).then(res => {

				console.log('上报', res);
			});
		},
		addIosGuide() {
			this.zwyRequest({
				url: '/cdp/personal/show/once/daily/info/DOU_YIN_FAVORITE_IOS',
				header: {
					'content-type': 'application/json'
				},
				method: 'post'
			}).then(res => {
				console.log('上报---ios', res);
			});
		},
		isEnded() {
			this.$emit('ended');
		},
		play() {
			this.$emit('play');
		},
		setPlayNow() {
			this.palyFlag = true
			this.playNow()
		},
		playNow() {
			this.showLoading = true;
			if (this.videoContent) {
				if (this.index == this.currentIndex) {
					console.log('this.videoContent', this.videoContent);
					this.videoContent.play();
					console.log("play")
					this.isPlayNow = true;
				} else {
					this.videoContent.pause();
					this.isPlayNow = false;
				}
			}

		}
	}
};
</script>

<style lang="scss">
.zwyVideoBox {
	bottom: auto;
	background-color: black;
	position: absolute;
	left: 0;
	width: 100%;
	z-index: 98;
}

.zwyVideo {
	width: 100%;
	background-color: black;
	height: 100%;
	will-change: transform;
}
</style>
